package com.xm.xmapp.http;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.TypeReference;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;
import com.xm.xmapp.LoginActivity;
import com.xm.xmapp.app.MyAppcation;
import com.xm.xmapp.exception.MyException;
import com.xm.xmapp.request.bean.BaseBeanRequest;
import com.xm.xmapp.response.bean.BaseBeanResponse;
import com.xm.xmapp.response.bean.ResponseUserBean;
import com.xm.xmapp.tools.BeanTools;
import com.xm.xmapp.tools.Log;
import com.xm.xmapp.tools.MyCache;
import com.xm.xmapp.tools.Tools;

public class PostRequest extends Request<String> {

	public BaseBeanRequest requestBean;
	public GetDataErrorListener errorListener;
	public Listener<String> listener;

	public PostRequest(int method, BaseBeanRequest requestBean, Listener<String> listener,
			GetDataErrorListener errorListener) {

		super(method, requestBean.getUrl(), errorListener);
		this.requestBean = requestBean;
		this.errorListener = errorListener;
		this.listener = listener;
		ResponseUserBean bean = MyAppcation.getMyAppcation().getUserBean();
		if (bean != null) {
			this.requestBean.uid = bean.user_id;
			this.requestBean.token = (bean.token);
		} else {
			this.requestBean.uid = (null);
			this.requestBean.token = (null);
		}

	}

	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		Map<String, String> map = new HashMap<String, String>();
		map = BeanTools.getMap(requestBean);
		return map;

	}

	/**
	 * Returns the raw POST or PUT body to be sent.
	 * 
	 * @throws AuthFailureError
	 *             in the event of auth failure
	 */
	public byte[] getBody() throws AuthFailureError {

		byte[] byteSize = null;

		Map<String, String> params = getParams();
		if (params != null && params.size() > 0) {
			return encodeParameters(params, getParamsEncoding());
		}
		return byteSize;

	}

	/**
	 * Converts <code>params</code> into an application/x-www-form-urlencoded
	 * encoded string.
	 */
	private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
		StringBuilder encodedParams = new StringBuilder();
		StringBuilder str = new StringBuilder();
		try {
			for (Map.Entry<String, String> entry : params.entrySet()) {
				if (!URLEncoder.encode(entry.getKey(), "UTF-8").equals("sign")) {
					encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
					encodedParams.append('=');
					encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
					encodedParams.append('&');
				} else {
					str.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
					str.append('=');
					str.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
				}
			}
			encodedParams.append(str);
			Log.d("Request", encodedParams.toString());

			return encodedParams.toString().getBytes(paramsEncoding);
		} catch (UnsupportedEncodingException uee) {
			throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
		}
	}

	@Override
	protected Response<String> parseNetworkResponse(NetworkResponse response) {
		//

		String str = null;
		try {
			str = new String(response.data, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return Response.success(str, HttpHeaderParser.parseCacheHeaders(response));
	}

	@Override
	protected void deliverResponse(String response) {

		try {
			final BaseBeanResponse<String> data = JSON.parseObject(response,
					new TypeReference<BaseBeanResponse<String>>() {
					});
			if (requestBean.isData()) {
				if (data.errCode == -999) {
					MyAppcation.getMyAppcation().clearUserBean();
					if (errorListener != null)
						errorListener.onErrorResponse(null, response);
					Intent intent = new Intent(MyAppcation.getMyAppcation(), LoginActivity.class);
					Activity activity = MyAppcation.getMyAppcation().getTopActivity();
					if (activity == null) {
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
						MyAppcation.getMyAppcation().startActivity(intent);
					} else {
						activity.startActivity(intent);
					}
				} else {
					listener.onResponse(response);
				}

			} else {
				switch (data.errCode) {
				case 0:
					listener.onResponse(data.data);
					if (requestBean.isCache()) {
						MyCache.getMyCache().putCache(requestBean.getCacheString(), data.data);
					}
					break;
				case -1:
					Tools.showMessage(data.errMsg);
					if (errorListener != null)
						errorListener.onErrorResponse(null, response);
					break;

				case 3001:
					Tools.showMessage(data.errMsg);
					if (errorListener != null)
						errorListener.onErrorResponse(null, data.errCode + "");
					break;

				case 10002:
					Tools.showMessage(data.errMsg);
					if (errorListener != null)
						errorListener.onErrorResponse(null, data.errCode + "");
					break;

				case 10003:
					if (errorListener != null)
						errorListener.onErrorResponse(null, response);
					break;
				case 10004:
					if (listener != null)
						listener.onResponse(response);
					break;
				case -999:

					MyAppcation.getMyAppcation().clearUserBean();
					if (errorListener != null)
						errorListener.onErrorResponse(null, response);
					Intent intent = new Intent(MyAppcation.getMyAppcation(), LoginActivity.class);
					Activity activity = MyAppcation.getMyAppcation().getTopActivity();
					if (activity == null) {
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
						MyAppcation.getMyAppcation().startActivity(intent);
					} else {
						activity.startActivity(intent);
					}

					break;

				default:

					break;
				}

			}
		} catch (Exception e) {
			MyException.printStackTrace(e);
			if (e instanceof JSONException) {
				Tools.showMessage("解析错误");
			} else {
				Tools.showMessage("其他错误");
			}

			if (errorListener != null)
				errorListener.onErrorResponse(null, response);
		}

	}

}
